package com.google.appengine.a4ieve.servlets.resources;

import com.google.appengine.a4ieve.Const;
import com.google.appengine.a4ieve.entities.StudentWrapper;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

class AddStudentServant implements Servant {

    private static final String NICKNAME = "studentNickName";
//    private static final String STUDENT_GROUP = "studentGroupName";
    private static final String STUDENT_FULL_NAME = "studentFullName";

    private static final Logger LOG = Logger.getLogger(AddStudentServant.class.getName());

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp){
        DatastoreService service = DatastoreServiceFactory.getDatastoreService();
        String userId = req.getParameter(NICKNAME); //all google names are saved in lowercase for search simplicity purposes
//        String groupId = req.getParameter(STUDENT_GROUP);
        String groupId = (String)req.getSession().getAttribute(Const.GROUP);
        String name = req.getParameter(STUDENT_FULL_NAME);
        if (userId == null) {
            JSONObject request = (JSONObject)req.getAttribute(Const.INNER_JSON);
            userId = request.getString(NICKNAME);
            name = request.getString(STUDENT_FULL_NAME);
        }
        StudentWrapper studentObject = new StudentWrapper.StudentBuilder().googleId(userId.toLowerCase())
                .groupId(groupId).name(name).build();
        Entity curator = studentObject.getEntity();
        service.put(curator);
        try {
            Const.SUCCESS_OBJECT.write(resp.getWriter());
        } catch (IOException e) {
            LOG.severe("Error while writing response " + e);
        }
    }
}